package service.impl;

import utils.MyBatisUtils;
import dao.AfterSaleRuleMapper;
import entity.AfterSaleRule;
import service.AfterSaleRuleService;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * 售后规则服务实现类
 */
public class AfterSaleRuleServiceImpl implements AfterSaleRuleService {

    @Override
    public void createRule(AfterSaleRule rule) {
        try (SqlSession sqlSession = MyBatisUtils.getSqlSession(false)) {
            AfterSaleRuleMapper mapper = sqlSession.getMapper(AfterSaleRuleMapper.class);
            mapper.insert(rule);
            sqlSession.commit();
        } catch (Exception e) {
            throw new RuntimeException("创建售后规则失败: " + e.getMessage());
        }
    }

    @Override
    public AfterSaleRule getRuleById(Long id) {
        try (SqlSession sqlSession = MyBatisUtils.getSqlSession()) {
            AfterSaleRuleMapper mapper = sqlSession.getMapper(AfterSaleRuleMapper.class);
            return mapper.selectById(id);
        }
    }

    @Override
    public List<AfterSaleRule> getAllRules() {
        try (SqlSession sqlSession = MyBatisUtils.getSqlSession()) {
            AfterSaleRuleMapper mapper = sqlSession.getMapper(AfterSaleRuleMapper.class);
            return mapper.selectAll();
        }
    }

    @Override
    public List<AfterSaleRule> getRulesByCategory(String category) {
        try (SqlSession sqlSession = MyBatisUtils.getSqlSession()) {
            AfterSaleRuleMapper mapper = sqlSession.getMapper(AfterSaleRuleMapper.class);
            return mapper.selectByCategory(category);
        }
    }

    @Override
    public void updateRule(AfterSaleRule rule) {
        try (SqlSession sqlSession = MyBatisUtils.getSqlSession(false)) {
            AfterSaleRuleMapper mapper = sqlSession.getMapper(AfterSaleRuleMapper.class);
            mapper.updateById(rule);
            sqlSession.commit();
        } catch (Exception e) {
            throw new RuntimeException("更新售后规则失败: " + e.getMessage());
        }
    }

    @Override
    public void deleteRule(Long id) {
        try (SqlSession sqlSession = MyBatisUtils.getSqlSession(false)) {
            AfterSaleRuleMapper mapper = sqlSession.getMapper(AfterSaleRuleMapper.class);
            mapper.deleteById(id);
            sqlSession.commit();
        } catch (Exception e) {
            throw new RuntimeException("删除售后规则失败: " + e.getMessage());
        }
    }
}
